<template>
  <div class="articles-container">
    <div class="page-header">
      <h2>文章管理</h2>
      <el-button type="primary" @click="handleAdd">发布文章</el-button>
    </div>

    <!-- 搜索和过滤 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="标题">
          <el-input v-model="searchForm.title" placeholder="请输入文章标题" clearable />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
            <el-option label="健康知识" value="health" />
            <el-option label="养生保健" value="wellness" />
            <el-option label="医疗科普" value="medical" />
            <el-option label="专家观点" value="expert" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="草稿" value="draft" />
            <el-option label="已发布" value="published" />
            <el-option label="已下架" value="offline" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 文章列表 -->
    <el-table :data="articleList" border style="width: 100%">
      <el-table-column prop="article_id" label="ID" width="80" />
      <el-table-column label="封面" width="120">
        <template #default="{ row }">
          <el-image 
            :src="row.cover_image" 
            :preview-src-list="[row.cover_image]"
            fit="cover"
            style="width: 100px; height: 60px"
          >
            <template #error>
              <div class="image-placeholder">暂无封面</div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
      <el-table-column prop="category" label="分类" width="120">
        <template #default="{ row }">
          <el-tag>{{ getCategoryText(row.category) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="author" label="作者" width="120" />
      <el-table-column prop="view_count" label="浏览量" width="100" />
      <el-table-column prop="comment_count" label="评论数" width="100" />
      <el-table-column prop="publish_time" label="发布时间" width="180" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleView(row)">查看</el-button>
          <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button 
            size="small" 
            :type="row.status === 'published' ? 'warning' : 'success'"
            @click="handleToggleStatus(row)"
          >{{ row.status === 'published' ? '下架' : '发布' }}</el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="handleDelete(row)"
            v-if="row.status !== 'published'"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 查看文章详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="文章详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="文章ID">{{ currentArticle.article_id }}</el-descriptions-item>
        <el-descriptions-item label="标题">{{ currentArticle.title }}</el-descriptions-item>
        <el-descriptions-item label="分类">{{ getCategoryText(currentArticle.category) }}</el-descriptions-item>
        <el-descriptions-item label="作者">{{ currentArticle.author }}</el-descriptions-item>
        <el-descriptions-item label="浏览量">{{ currentArticle.view_count }}</el-descriptions-item>
        <el-descriptions-item label="评论数">{{ currentArticle.comment_count }}</el-descriptions-item>
        <el-descriptions-item label="发布时间">{{ currentArticle.publish_time }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ getStatusText(currentArticle.status) }}</el-descriptions-item>
        <el-descriptions-item label="摘要" :span="2">{{ currentArticle.summary }}</el-descriptions-item>
      </el-descriptions>

      <div class="section-title">文章内容</div>
      <div class="article-content" v-html="currentArticle.content"></div>
    </el-dialog>

    <!-- 编辑/发布文章对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="isEdit ? '编辑文章' : '发布文章'"
      width="800px"
    >
      <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px">
        <el-form-item label="文章封面" prop="cover_image">
          <el-upload
            class="cover-upload"
            action="#"
            :auto-upload="false"
            :on-change="handleCoverChange"
            accept="image/*"
          >
            <template #trigger>
              <el-button type="primary">选择封面</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">建议尺寸 16:9，支持jpg、png格式</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="editForm.category" placeholder="请选择分类">
            <el-option label="健康知识" value="health" />
            <el-option label="养生保健" value="wellness" />
            <el-option label="医疗科普" value="medical" />
            <el-option label="专家观点" value="expert" />
          </el-select>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="editForm.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="摘要" prop="summary">
          <el-input 
            type="textarea" 
            v-model="editForm.summary" 
            rows="3"
            placeholder="请输入文章摘要"
          />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <div class="editor-container">
            <!-- TODO: 集成富文本编辑器 -->
            <el-input 
              type="textarea" 
              v-model="editForm.content" 
              rows="10"
              placeholder="请输入文章内容"
            />
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio label="draft">保存草稿</el-radio>
            <el-radio label="published">立即发布</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = ref({
  title: '',
  category: '',
  status: '',
  dateRange: []
})

// 文章列表数据
const articleList = ref([
  {
    article_id: 1,
    title: '健康饮食指南：如何科学搭配每日营养',
    category: 'health',
    cover_image: 'https://example.com/article1.jpg',
    author: '张三',
    view_count: 1500,
    comment_count: 30,
    publish_time: '2024-03-15 10:00:00',
    status: 'published',
    summary: '本文介绍了健康饮食的基本原则和科学搭配方法...',
    content: '<p>详细的健康饮食指南内容...</p>'
  },
  {
    article_id: 2,
    title: '中医养生：春季养生要点',
    category: 'wellness',
    cover_image: 'https://example.com/article2.jpg',
    author: '李四',
    view_count: 1200,
    comment_count: 25,
    publish_time: '2024-03-16 14:00:00',
    status: 'draft',
    summary: '春季养生的关键点和注意事项...',
    content: '<p>春季养生的具体内容...</p>'
  },
  {
    article_id: 3,
    title: '最新医疗技术发展动态',
    category: 'medical',
    cover_image: 'https://example.com/article3.jpg',
    author: '王五',
    view_count: 2000,
    comment_count: 45,
    publish_time: '2024-03-17 16:00:00',
    status: 'offline',
    summary: '医疗技术领域最新突破和发展趋势...',
    content: '<p>医疗技术发展的详细内容...</p>'
  }
])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(3)

// 对话框相关
const viewDialogVisible = ref(false)
const editDialogVisible = ref(false)
const isEdit = ref(false)
const currentArticle = ref({})
const editFormRef = ref(null)

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择文章分类', trigger: 'change' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ],
  summary: [
    { required: true, message: '请输入文章摘要', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择发布状态', trigger: 'change' }
  ]
}

// 编辑表单
const editForm = ref({
  title: '',
  category: '',
  author: '',
  summary: '',
  content: '',
  cover_image: '',
  status: 'draft'
})

// 获取分类文本
const getCategoryText = (category) => {
  const texts = {
    'health': '健康知识',
    'wellness': '养生保健',
    'medical': '医疗科普',
    'expert': '专家观点'
  }
  return texts[category] || category
}

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    'draft': 'info',
    'published': 'success',
    'offline': 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    'draft': '草稿',
    'published': '已发布',
    'offline': '已下架'
  }
  return texts[status] || status
}

// 搜索处理
const handleSearch = () => {
  // TODO: 实现搜索逻辑
  console.log('搜索条件:', searchForm.value)
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    title: '',
    category: '',
    status: '',
    dateRange: []
  }
  handleSearch()
}

// 查看文章
const handleView = (row) => {
  currentArticle.value = { ...row }
  viewDialogVisible.value = true
}

// 添加文章
const handleAdd = () => {
  isEdit.value = false
  editForm.value = {
    title: '',
    category: '',
    author: '',
    summary: '',
    content: '',
    cover_image: '',
    status: 'draft'
  }
  editDialogVisible.value = true
}

// 编辑文章
const handleEdit = (row) => {
  isEdit.value = true
  editForm.value = { ...row }
  editDialogVisible.value = true
}

// 切换文章状态
const handleToggleStatus = (row) => {
  const action = row.status === 'published' ? '下架' : '发布'
  ElMessageBox.confirm(
    `确定要${action}该文章吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // TODO: 实现状态切换逻辑
    ElMessage.success(`${action}成功`)
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 删除文章
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除文章 "${row.title}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // TODO: 实现删除逻辑
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 封面图片改变
const handleCoverChange = (file) => {
  // TODO: 处理封面图片上传
  console.log('选择的封面图片:', file)
}

// 保存文章
const handleSave = () => {
  editFormRef.value?.validate((valid) => {
    if (valid) {
      // TODO: 实现保存逻辑
      ElMessage.success(isEdit.value ? '编辑成功' : '发布成功')
      editDialogVisible.value = false
    }
  })
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  // TODO: 重新加载数据
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  // TODO: 重新加载数据
}
</script>

<style scoped>
.articles-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.image-placeholder {
  width: 100px;
  height: 60px;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 12px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.article-content {
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
</style>